package com.qmock.pay.http;

import org.apache.log4j.Logger;
import org.webbitserver.HttpControl;
import org.webbitserver.HttpHandler;
import org.webbitserver.HttpRequest;
import org.webbitserver.HttpResponse;

import java.util.Map;

/**
 * @author tianqing.wang
 */
public class ConfigHttpHandler implements HttpHandler {
    private Logger logger = Logger.getLogger(ConfigHttpHandler.class);
    @Override
    public void handleHttpRequest(HttpRequest request, HttpResponse response, HttpControl control) throws Exception {
        try{
            if(request.postParam("status")!=null){
                ParameterParse parameterParse=new ParameterParse(request);
                if(request.postParam("status").equals("start")){
                    logger.info("服务器接收到了响应配置文件，正在初始化.......");
                    parameterParse.remove("status");
                    InfoMap.addInfo("info",new ExpectResponse(new ParameterPairs(parameterParse.getParameters())));
                    printMap(((ExpectResponse)InfoMap.getExpectResponse("info")).getResponse());
                    response.header("Content-type", "text/html").content("it`s the success callback>").end();
                }else if(request.postParam("status").equals("over")){
                    InfoMap.remove("info");
                    response.header("Content-type", "text/html").content("it`s the success callback>").end();
                }
            }else{
                response.header("Content-type", "text/html").content("it`s no parameters.</br>").end();
            }
        }catch(Exception e){
            response.header("Content-type","text/html").content("the http connection is closed").end();
        }

    }
    private void printMap(Map<String,String> map){
        for(Map.Entry<String,String> entry:map.entrySet()){
            logger.info("响应的参数-->"+" key: "+entry.getKey()+", value: "+entry.getValue());
        }
    }
}
